﻿using LitJson;
using System.Collections.Generic;
using System.IO;
using UnityEngine;
using UnityEngine.SceneManagement;

public class PlayerManager
{
    public string ConfigPathSelf;
    public static PlayerManager Instance = new PlayerManager();
    public Player playerSelf { get { return m_PlayerSelf; } }
    JsonData m_JsonData;


    List<Player> m_Players = new List<Player>();
    Player m_PlayerSelf = new Player();

    public PlayerManager()
    {
        ConfigPathSelf = Utils.GetDataPath() + "Player.data";
    }
    public void InitSystem()
    {
        m_JsonData = Utils.LoadJson(ConfigPathSelf);
        if(m_JsonData == null)
        {
            MessageShow.Instance.Error("we detected the player's archive was damaged.");
        }
        Load(m_JsonData);
    }
    public void InitWorld(Scene scene, LoadSceneMode mode)
    {
        Debug.Log("initWorld");
        Load(m_JsonData);
    }
    public void ShutdownWorld()
    {
        Debug.Log("shutdownWorld");
        Save(false);
    }
    public JsonData Save(bool saveToFile = true)
    {
        JsonData root = new JsonData();
        root["Self"] = playerSelf.Save();

        if(saveToFile)
        {
            string data = root.ToJson();
            using (FileStream fs = new FileStream(ConfigPathSelf, FileMode.Create, FileAccess.Write))
            {
                byte[] array = System.Text.Encoding.UTF8.GetBytes(data);
                fs.Write(array, 0, (int)array.Length);
                fs.Close();
            }
        }
        m_JsonData = root;
        return root;
    }

    void Load(JsonData json)
    {
        m_JsonData = json;
        IDictionary<string, JsonData> jsond = json.ValueAsObject();
        if (jsond.ContainsKey("Self"))
        {
            m_PlayerSelf = new Player();
            m_PlayerSelf.Load(jsond["Self"]);
        }
    }
}